package com.weixing.mall.provider.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.weixing.mall.base.constant.GlobalConstant;
import com.weixing.mall.base.wrapper.Result;
import com.weixing.mall.provider.api.model.vo.OrderItemVo;
import com.weixing.mall.provider.api.service.MemberServiceRpc;
import com.weixing.mall.provider.api.service.OrderServiceRpc;
import com.weixing.mall.provider.mapper.BuyerShowImgMapper;
import com.weixing.mall.provider.mapper.BuyerShowMapper;
import com.weixing.mall.provider.model.domain.BuyerShow;
import com.weixing.mall.provider.model.domain.BuyerShowImg;
import com.weixing.mall.provider.model.dto.BuyerShowChgStatusDto;
import com.weixing.mall.provider.model.dto.BuyerShowDto;
import com.weixing.mall.provider.model.dto.UploadBuyerShowDto;
import com.weixing.mall.provider.model.enums.IsShowEnum;
import com.weixing.mall.provider.model.enums.ReviewEnum;
import com.weixing.mall.provider.model.enums.ShowFromEnum;
import com.weixing.mall.provider.model.query.BuyerShowQuery;
import com.weixing.mall.provider.model.vo.BuyerShowDetilVo;
import com.weixing.mall.provider.model.vo.BuyerShowListVo;
import com.weixing.mall.provider.model.vo.BuyerShowVo;
import com.weixing.mall.provider.service.IBuyerShowService;
import com.weixing.mall.provider.service.IGoodsImgService;
import com.weixing.mall.provider.service.IPraiseLogService;
import lombok.Synchronized;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author wx
 * @Date 2019/8/7 14:48
 * @Version 1.0
 */

/**
 * <p>
 * 商品模块-商品买家秀 服务实现类
 * </p>
 *
 * @author Small
 * @since 2019-11-20
 */
@Service
public class BuyerShowServiceImpl extends ServiceImpl<BuyerShowMapper, BuyerShow> implements IBuyerShowService {

    @Autowired
    private BuyerShowImgMapper buyerShowImgMapper;
    @Autowired
    private OrderServiceRpc orderServiceRpc;
    @Autowired
    private IPraiseLogService praiseLogService;
    @Autowired
    private IGoodsImgService goodsImgService;
    @Autowired
    private MemberServiceRpc memberServiceRpc;

    @Override
    public IPage<BuyerShowVo> findOfPage(Page page, BuyerShowQuery buyerShowQuery) {
        IPage<BuyerShowVo> pageList = baseMapper.selectList(page, buyerShowQuery);
        List<BuyerShowVo> records = pageList.getRecords();
        for (BuyerShowVo record : records) {
            List<BuyerShowImg> imgList = buyerShowImgMapper.selectByBuyerShowId(record.getId());
            ArrayList<String> list = new ArrayList<>();
            for (BuyerShowImg buyerShowImg : imgList) {
                list.add(buyerShowImg.getImg());
            }
            record.setImg(list);
        }
        for (BuyerShowVo record : records) {
            if (record.getShowFrom() == 2) {
                record.setAvator(record.getMAvator());
                record.setNickName(record.getMNickName());
                Result<OrderItemVo> orderItemVoResult = orderServiceRpc.selectById(record.getOrderId());
                OrderItemVo data = orderItemVoResult.getData();
                if (orderItemVoResult.isSuccess() && null != data) {
                    record.setOrderSn(data.getOrderSn());
                }

            }
        }

        return pageList;
    }

    @Override
    public void save(BuyerShowDto buyerShowDto, Long uid) {
        BuyerShow buyerShow = new BuyerShow();
        BeanUtils.copyProperties(buyerShowDto, buyerShow);
        buyerShow.setAuditStatus(buyerShowDto.getAuditStatus().getValue());
        BuyerShowImg buyerShowImg = new BuyerShowImg();
        if (null == buyerShowDto.getId()) {
            buyerShow.setShowFrom(1);
            buyerShow.setCreatedTime(new Date());
            buyerShow.setShowFrom(ShowFromEnum.TYPE1.getValue());
            baseMapper.insert(buyerShow);
            String[] img = buyerShowDto.getImg();
            for (int i = 0; i < img.length; i++) {
                buyerShowImg.setBuyerShowId(buyerShow.getId());
                buyerShowImg.setImg(img[i]);
                buyerShowImgMapper.insert(buyerShowImg);
            }
        } else {
            buyerShow.setUpdatedTime(new Date());
            updateById(buyerShow);
            BuyerShow memberShow = getById(buyerShow.getId());
            if (ObjectUtil.isNotEmpty(memberShow) && ReviewEnum.ADOPT.getValue().equals(buyerShow.getAuditStatus())) {//审核通过奖励积分
                memberServiceRpc.bonusPointsHandle(memberShow.getMemberId(), GlobalConstant.SHOW_POINT, null, uid);
            }
        }
    }

    @Override
    public void delAll(int[] ids) {
        System.out.println(ids);
        baseMapper.delAll(ids);
    }

    @Override
    public BuyerShowDetilVo queryDetails(Long id) {
        BuyerShowDetilVo buyerShowDetilVo = baseMapper.queryDetails(id);
        //查询对应买家秀id的买家秀图片添加进list
        List<BuyerShowImg> list = buyerShowImgMapper.selectByBuyerShowId(id);
        List<String> img = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            img.add(list.get(i).getImg());
        }
        buyerShowDetilVo.setImg(img);
        //来源于会员评价，把会员的头像和昵称展示出来（这样后台添加的和用户评价的可以同时显示）
        if (buyerShowDetilVo.getShowFrom().getValue() == 2) {
            buyerShowDetilVo.setAvator(buyerShowDetilVo.getUserAvator());
            buyerShowDetilVo.setNickName(buyerShowDetilVo.getUserNickName());
        }
        //添加商品图片
        if (buyerShowDetilVo != null && buyerShowDetilVo.getGoodsId() != null) {
            buyerShowDetilVo.setGoodsImg(goodsImgService.selectGoodsImg(buyerShowDetilVo.getGoodsId()));
        }
        return buyerShowDetilVo;

    }

    @Override
    @Synchronized
    public void updateStatus(BuyerShowChgStatusDto buyerShowChgStatusDto) {
        BuyerShow buyerShow = getById(buyerShowChgStatusDto.getBuyerShowId());
        if (1 == buyerShowChgStatusDto.getFlag()) {
            if (buyerShow.getPraiseCount() == null) {
                buyerShowChgStatusDto.setPraiseCount(1);
            } else {
                buyerShowChgStatusDto.setPraiseCount(buyerShow.getPraiseCount() + 1);
            }
        } else {
            if (buyerShow.getPraiseCount() == null) {
                buyerShowChgStatusDto.setPraiseCount(0);
            } else {
                buyerShowChgStatusDto.setPraiseCount(buyerShow.getPraiseCount() - 1);
            }
        }
        baseMapper.updateStatus(buyerShowChgStatusDto);
        /*if(buyerShow != null){
            if(1==buyerShowChgStatusDto.getFlag()){
                buyerShow.setPraiseCount(buyerShow.getPraiseCount() + 1);
            }else{
                buyerShow.setPraiseCount(buyerShow.getPraiseCount() - 1);
            }
            updateById(buyerShow);
        }*/
    }

    @Override
    public void uploadBuyerShow(UploadBuyerShowDto uploadBuyerShowDto, Long mid) {
        BuyerShow buyerShow = new BuyerShow();
        BeanUtils.copyProperties(uploadBuyerShowDto, buyerShow);
        //添加会员id（默认当前登录人）
        buyerShow.setMemberId(mid);
        //来源：会员上传买家秀
        buyerShow.setShowFrom(ShowFromEnum.TYPE2.getValue());
        //新上传的待审核
        buyerShow.setAuditStatus(ReviewEnum.TO_AUDITED.getValue());
        //默认新上传的不展示，审核通过再展示
        buyerShow.setIsShow(IsShowEnum.TO_AUDITED.getValue());
        baseMapper.insert(buyerShow);
        String img = uploadBuyerShowDto.getImg();
        BuyerShowImg buyerShowImg = new BuyerShowImg();
        String[] imgs = img.split(",");
        for (int i = 0; i < imgs.length; i++) {
            buyerShowImg.setBuyerShowId(buyerShow.getId());
            buyerShowImg.setImg(imgs[i]);
            buyerShowImg.setCreatedTime(new Date());
            buyerShowImgMapper.insert(buyerShowImg);
        }
    }

    @Override
    public IPage<BuyerShowListVo> selectListOfPage(Page page, Long goodsId, Long mid) {
        IPage<BuyerShowListVo> pageList = null;
        if (null == goodsId) {
            pageList = baseMapper.selectAllListOfPage(page);
        } else {
            pageList = baseMapper.selectListOfPage(page, goodsId);
        }
        List<BuyerShowListVo> list = pageList.getRecords();
        //循环list处理内部图片list/和昵称头像
        for (int i = 0; i < list.size(); i++) {
            BuyerShowListVo buyerShowListVo = list.get(i);
            //查询对应买家秀id的买家秀图片添加进list
            List<BuyerShowImg> BuyerShowImgList = buyerShowImgMapper.selectByBuyerShowId(buyerShowListVo.getId());
            List<String> img = new ArrayList<>();
            for (int j = 0; j < BuyerShowImgList.size(); j++) {
                img.add(BuyerShowImgList.get(j).getImg());
            }
            buyerShowListVo.setImg(img);
            //来源是会员评价，处理昵称头像
            if (buyerShowListVo.getShowFrom().getValue() == 2) {
                buyerShowListVo.setNickName(buyerShowListVo.getUserNickName());
                buyerShowListVo.setAvator(buyerShowListVo.getUserAvator());
            }

            //判断是否为买家秀记录点赞
            if(null == mid){
                buyerShowListVo.setIsPraise(0);
            }else{
                buyerShowListVo.setIsPraise(praiseLogService.checkPraise(buyerShowListVo.getId(), mid) ? 1 : 0);
            }
        }
        pageList.setRecords(list);
        return pageList;
    }
}
